package com.example.boos.login;

import android.annotation.SuppressLint;
import android.content.ComponentName;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;

import com.bumptech.glide.Glide;
import com.example.boos.HttpUtil.MyPost;
import com.example.boos.R;
import com.example.boos.context.BossInfo;
import com.example.boos.pojo.Boss;
import com.example.boos.stores.stores_activity;
import com.example.boos.util.MyCountDownUtil;
import com.example.boos.util.MyThreadPool;
import com.example.boos.util.RequestPermissionUtil;
import com.example.boos.util.ShowPopuWIndow;


import java.util.HashMap;
import java.util.Map;

import static android.widget.Toast.LENGTH_SHORT;

public class login extends AppCompatActivity {

    private LoginFragment loginFragment;
    private RegisterFragment registerFragment;
    private String bossTelephone;
    private String bossPassword;

    private ImageView bossImage;
    private TextView bossImageStr;

    Handler handler = new Handler(){
        @SuppressLint("HandlerLeak")
        @Override
        public void handleMessage(@NonNull Message msg) {
            switch (msg.what){
                case 1:
                    if(BossInfo.boss == null || BossInfo.boss.getId() == null){
                        Toast.makeText(login.this,"登录失败，请重试！",Toast.LENGTH_SHORT).show();
                    }else{
                        // 登录成功，进入到骑手页面
                        Toast.makeText(login.this,"登录成功，即将进入主页面！",Toast.LENGTH_SHORT).show();
                        // 记录到 Sharepreference中
                        editor = sharedPreferences.edit();
                        editor.putString("bossTelephone", BossInfo.boss.getTelephone());
                        editor.putString("bossName", BossInfo.boss.getBossName());
                        editor.putString("bossPwd", BossInfo.boss.getPassword());
                        editor.putInt("bossId", BossInfo.boss.getId());
                        editor.putString("bossEmail", BossInfo.boss.getEmail());
                        editor.putString("bossImage", BossInfo.boss.getImage());
                        editor.putBoolean("isLogin",true);
                        editor.commit();
                        BossInfo.bossId = BossInfo.boss.getId();
                        // 跳转到骑手页面
                        Intent intent = new Intent();
                        intent.setComponent(new ComponentName(login.this, stores_activity.class));
                        login.this.startActivity(intent);
                    }
                    break;
                case 2:
                    // 将图片地址保存
                    bossImageStr.setText((String)msg.obj);
                    break;
                case 3:
                    // 验证码倒计时
                    MyCountDownUtil myCountDownUtil = new MyCountDownUtil(60000,1000,(Button) msg.obj);
                    myCountDownUtil.start();
                    break;
                case 4:
                    Toast.makeText(login.this,"获取验证码失败，请重试！",LENGTH_SHORT).show();
                    break;
                case 5:
                    Toast.makeText(login.this,"验证码错误,请重试！",LENGTH_SHORT).show();
                    break;
                case 6:
                    //注册成功，直接进入主页面
                    Boss boss = (Boss) msg.obj;
                    if(boss !=null &&boss.getId() != null){
                        Toast.makeText(login.this,"登录成功，即将进入主页面！",Toast.LENGTH_SHORT).show();
                        // 记录到 Sharepreference中
                        BossInfo.boss = boss;
                        editor = sharedPreferences.edit();
                        editor.putString("bossTelephone", BossInfo.boss.getTelephone());
                        editor.putString("bossName", BossInfo.boss.getBossName());
                        editor.putString("bossPwd", BossInfo.boss.getPassword());
                        editor.putInt("bossId", BossInfo.boss.getId());
                        editor.putString("bossEmail", BossInfo.boss.getEmail());
                        editor.putString("bossImage", BossInfo.boss.getImage());
                        editor.putBoolean("isLogin",true);
                        editor.commit();
                        BossInfo.bossId = BossInfo.boss.getId();
                        // 跳转到骑手页面
                        Intent intent = new Intent();
                        intent.setComponent(new ComponentName(login.this, stores_activity.class));
                        login.this.startActivity(intent);
                    }else{
                        Toast.makeText(login.this,"用户名重复！",LENGTH_SHORT).show();
                    }
                    break;
            }
        }
    };
    private SharedPreferences sharedPreferences;
    SharedPreferences.Editor editor ;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        // 先判断是否为登录过
        sharedPreferences = getSharedPreferences("BossInfo",MODE_PRIVATE);
        Boolean isLogin = sharedPreferences.getBoolean("isLogin",false);
        //sharedPreferences.edit().clear().commit();
        if(isLogin){
            // 登录过
            // 获取到骑手的信息
            String bossName = sharedPreferences.getString("bossName","未登录");
            String telephone = sharedPreferences.getString("bossTelephone","未登录");
            String pwd = sharedPreferences.getString("bossPwd","");
            String image = sharedPreferences.getString("bossImage","");
            String email = sharedPreferences.getString("bossEmail","");
            Integer bossId = sharedPreferences.getInt("bossId",-1);
            Boss boss = new Boss();
            boss.setId(bossId);
            boss.setTelephone(telephone);
            boss.setBossName(bossName);
            boss.setEmail(email);
            boss.setImage(image);
            boss.setPassword(pwd);
            BossInfo.boss = boss;
            BossInfo.bossId = bossId;
            Intent intent = new Intent();
            intent.setComponent(new ComponentName(login.this, stores_activity.class));
            login.this.startActivity(intent);
        }else{
            // 还未登录
            // 显示登录界面
            loginFragment = new LoginFragment(myLoginCallBack);
            FragmentManager fragmentManager = getSupportFragmentManager(); // Fragment管理器
            FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
            fragmentTransaction.add(R.id.myFragment,loginFragment).commitNow();
            RequestPermissionUtil.requestPermission(this);
        }
    }


    private LoginFragmentCallBack myLoginCallBack = new LoginFragmentCallBack() {
        @Override
        public void onTelephoneChanged(String telephone) {
            // 用户名改变
            bossTelephone = telephone;
        }

        @Override
        public void onPasswordChanged(String password) {
            // 密码改变
            bossPassword = password;
        }

        @Override
        public void LoginBtn() { // 登录按钮
            // 商家登录
            Map<String,String> param = new HashMap<>();
            param.put("tel", bossTelephone);
            param.put("pwd", bossPassword);
            MyThreadPool.doJob(new Runnable() {
                @Override
                public void run() {
                    BossInfo.boss = (Boss) MyPost.doPost("bossLogin",param);
                    Message msg = new Message();
                    msg.what = 1;
                    handler.sendMessage(msg);
                }
            });

        }

        @Override
        public void Register() {// 注册话，转换 Fragment
            //跳转到 注册页面
            registerFragment = new RegisterFragment(callBack);
            FragmentManager fragmentManager = getSupportFragmentManager(); // Fragment管理器
            FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
            fragmentTransaction.addToBackStack(null)
                    .replace(R.id.myFragment,registerFragment)
                    .commit();
        }
    };

    private RegisterFragmentCallBack callBack = new RegisterFragmentCallBack() {
        @Override
        public void changeUserImage() {
            ShowPopuWIndow.showPopueWindow(login.this,1);
        }

        @Override
        public void getVerifyCode(View btn, String email) {
            // 获取验证码操作
            MyThreadPool.doJob(new Runnable() {
                @Override
                public void run() {
                    Message msg = new Message();
                    Boolean isGet = (Boolean) MyPost.doPost("getVerifyCode",email);
                    if(isGet){
                        msg.what = 3; // 成功获取到验证码
                    }else{
                        msg.what = 4;  // 获取失败了
                    }
                    msg.obj = btn;
                    handler.sendMessage(msg);
                }
            });
        }

        @Override
        public void register(Boss user, String code) {
            // 注册操作，先验证验证码，再进行注册操作
            if(user.getEmail() == null || user.getEmail().equals("")){
                Toast.makeText(login.this,"请输入邮箱！",LENGTH_SHORT).show();
                return ;
            }
            if(user.getTelephone() == null || user.getTelephone().equals("")){
                Toast.makeText(login.this,"请输入手机号码！",LENGTH_SHORT).show();
                return ;
            }
            if(user.getBossName() == null || user.getBossName().equals("")){
                Toast.makeText(login.this,"请输入昵称！",LENGTH_SHORT).show();
                return ;
            }
            if(user.getImage() == null || user.getImage().equals("")){
                Toast.makeText(login.this,"请选择头像！",LENGTH_SHORT).show();
                return ;
            }
            if(code == null || code.equals("")){
                Toast.makeText(login.this,"请输入验证码！",LENGTH_SHORT).show();
                return ;
            }
            // 都检查无误，就发送注册请求，注册完毕后，携带参数返回到登录页面中
            MyThreadPool.doJob(new Runnable() {
                @Override
                public void run() {
                    Map<String,Object> param = new HashMap<>();
                    param.put("email",user.getEmail());
                    param.put("code",code);
                    Boolean result = (Boolean) MyPost.doPost("userVerifyCode",param);
                    Message msg = new Message();
                    if(result){
                        // 验证成功
                        Boss user1 = (Boss) MyPost.doPost("bossRegister",user);
                        msg.what = 6;
                        if(user1.getId() != null){
                            // 注册成功
                            msg.obj = user1;
                        }
                    }else{
                        // 验证失败
                        msg.what  =5;
                    }
                    handler.sendMessage(msg);
                }
            });
        }
    };

    @Override
    protected void onStart() {
        super.onStart();
        // 在这里获取到 Register的图片组件
        bossImage = findViewById(R.id.reg_userImage);
        bossImageStr = findViewById(R.id.userImageStr);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            // 如果是 相册返回的话
            if (requestCode == 1 && null != data) {
                Uri selectedImage = data.getData();
                String[] filePathColumn = {MediaStore.Images.Media.DATA};

                Cursor cursor = getContentResolver().query(selectedImage,
                        filePathColumn, null, null, null);
                cursor.moveToFirst();

                int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
                //获取到图片的本地地址
                final String picturePath = cursor.getString(columnIndex);
                // 显示图片
                //upload(picturePath);
                Glide.with(this).load(picturePath).into(bossImage);
                // 上传图片获取到src
                MyThreadPool.doJob(new Runnable() {
                    @Override
                    public void run() {
                        String url = (String) MyPost.uploadImage("getImageUrl",picturePath);
                        Message msg = new Message();
                        msg.obj = url;
                        msg.what = 2;
                        handler.sendMessage(msg);
                    }
                });
                cursor.close();
            }
        }
    }
}